package com.example.javaproject.jvm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * Description:
 * <br/>Author:  tianjinyong
 * <br/>Date:    2020/7/28 3:36 PM
 */
public class TestClass extends ClassLoader {
    private int mCount;

    public int getCount() {
        return mCount + 1;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class clazz = null;

        // 将包路径的(.)替换为斜线(/)
        String fileStub = name.replace(".", "/");
        String classFileName = fileStub + ".class";
        File classFile = new File(classFileName);

        if (classFile.exists()) {
            try {
                // 将Class文件的二进制数据读入数组
                byte[] raw = getBytes(classFile);
                // 调用ClassLoader的defineClass方法将二进制数据转换为Class对象
                clazz = defineClass(name, raw, 0, raw.length);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 如果clazz为null,表明加载失败，抛出异常
        if (null == clazz) {
            throw new ClassNotFoundException(name);
        }

        return clazz;
    }

    private byte[] getBytes(File classFile) throws Exception {
        long len = classFile.length();
        byte[] raw = new byte[(int) len];

        FileInputStream fin = new FileInputStream(classFile);
        //一次性读取Class文件的全部二进制数据
        int read = fin.read(raw);
        if (read != len) {
            throw new Exception("无法读取全部文件");
        }
        return raw;
    }


}
